package com.borqsprocessmanager.fragments;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.MainActivity;
import com.borqsprocessmanager.R;
import com.borqsprocessmanager.adapter.DroidWallAdapter;
import com.borqsprocessmanager.info.SectionInfo;
import com.borqsprocessmanager.util.DroidWallAPI;
import com.borqsprocessmanager.util.DroidWallAPI.DroidApp;
import com.borqsprocessmanager.util.Log;
import com.borqsprocessmanager.view.SwipeDismissListViewTouchListener;
import com.borqsprocessmanager.view.sectionlistview.PinnedHeaderListView;
import com.borqsprocessmanager.view.sectionlistview.SectionListAdapter;
import com.umeng.analytics.MobclickAgent;

public class NetWorkFrament extends BaseFragment implements OnClickListener {
    private final String TAG = "NetWorkFrament";

    private View layout, mHeader;
    // private TextView mNetButton, mWifiButton;
    private PinnedHeaderListView mListView;
    private DroidWallAdapter mItemAdapter;
    private ArrayList<DroidApp> mApps;

    private boolean isConfigChanged = false;

    // private ArrayList<ReceiverProcessInfo> mList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.res_fragment, null);
        return layout;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        findView(layout);
        mApps = initData();
        initView();
        setAdapter(mApps, mListView);
        setListener();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        if (mItemAdapter.isConfigChanged()) {
            Log.v(TAG, "applyOrSaveRules");
            applyOrSaveRules();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private void findView(View layout) {
        mListView = (PinnedHeaderListView) layout.findViewById(R.id.main_list);
        mHeader = mActivity.getLayoutInflater().inflate(R.layout.droid_head,
                mListView, false);
        // mNetButton = (TextView)
        // mHeader.findViewById(R.id.droid_head_text_3g);
        // mWifiButton = (TextView) mHeader
        // .findViewById(R.id.droid_head_text_wifi);
    }

    private ArrayList<DroidApp> initData() {
        // mList = new ArrayList<ReceiverProcessInfo>();
        ArrayList<DroidApp> apps = DroidWallAPI.getApps(App.mContext);
        sortDroidApp(apps);
        Log.v(TAG, "DroidApp.size===" + apps.size());
        return apps;
    }

    private void initView() {
        mListView.addHeaderView(mActivity.getLayoutInflater().inflate(
                R.layout.list_tile_head, null));
    }

    private void setListener() {
        // mNetButton.setOnClickListener(this);
        // mWifiButton.setOnClickListener(this);
        // mHeader.setOnClickListener(this);
        // mHeader.requestFocus();
    }

    private void setAdapter(ArrayList<DroidApp> applications,
            PinnedHeaderListView listView) {

        // applications.get(0).section_tag = SectionInfo.SECTION_HRAD_TAG;
        // applications.get(3).section_tag = SectionInfo.SECTION_HRAD_TAG;
        mItemAdapter = new DroidWallAdapter(App.mContext, applications);
        SectionListAdapter adapter = new SectionListAdapter(mItemAdapter,
                R.id.droid_heade);
        adapter.setOnClickListener(this);
        // listView.setFocusable(true);
        // listView.addHeaderView(mActivity.getLayoutInflater().inflate(
        // R.layout.list_tile_head, null));
        listView.setAdapter(adapter);
        listView.setOnScrollListener(adapter);
        listView.setPinnedHeaderView(mHeader);
    }

    private void sortDroidApp(ArrayList<DroidApp> apps) {

        Collections.sort(apps, new Comparator<DroidApp>() {
            @Override
            public int compare(DroidApp o1, DroidApp o2) {
                if ((o1.selected_wifi | o1.selected_3g) == (o2.selected_wifi | o2.selected_3g)) {
                    return o1.names[0].compareTo(o2.names[0]);
                }
                if (o1.selected_wifi || o1.selected_3g)
                    return -1;
                return 1;
            }
        });
    }

    /**
     * Apply or save iptable rules, showing a visual indication
     */
    private void applyOrSaveRules() {
        new Thread() {
            @Override
            public void run() {
                final boolean enabled = true;
                if (!DroidWallAPI.hasRootAccess(App.mContext, false))
                    return;
                if (enabled) {
                    if (DroidWallAPI.applyIptablesRules(App.mContext, false)) {
                        Log.v(TAG, "success");
                    }
                } else {
                    DroidWallAPI.saveRules(App.mContext);
                }
            }
        }.start();
        // final Handler handler;
        // final boolean enabled = true;
        // handler = new Handler() {
        // public void handleMessage(Message msg) {
        // if (!DroidWallAPI.hasRootAccess(App.mContext, false))
        // return;
        // if (enabled) {
        // if (DroidWallAPI.applyIptablesRules(App.mContext, false)) {
        // Log.v(TAG, "success");
        // }
        // } else {
        // DroidWallAPI.saveRules(App.mContext);
        // }
        // }
        // };
        // handler.sendEmptyMessageDelayed(0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.droid_head_text_3g:
            for (DroidApp app : mApps) {
                if (!app.selected_3g) {
                    app.selected_3g = false;
                } else {
                    app.selected_3g = true;
                }
            }
            mItemAdapter.notifyDataSetChanged();
            isConfigChanged = true;
            break;
        case R.id.droid_head_text_wifi:
            for (DroidApp app : mApps) {
                if (!app.selected_wifi) {
                    app.selected_wifi = false;
                } else {
                    app.selected_wifi = true;
                }
            }
            mItemAdapter.notifyDataSetChanged();
            isConfigChanged = true;
            break;

        default:
            break;
        }
    }
}
